# encoding: utf-8

#*******************************************************************************
#                                                                              *
#   ReadOnMac is free software: you can redistribute it and/or modify          *
#   it under the terms of the GNU General Public License as published by       *
#   the Free Software Foundation, either version 3 of the License, or          *
#   (at your option) any later version.                                        *
#                                                                              *
#   ReadOnMac is distributed in the hope that it will be useful,               *
#   but WITHOUT ANY WARRANTY; without even the implied warranty of             *
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
#   GNU General Public License for more details.                               *
#                                                                              *
#   You should have received a copy of the GNU General Public License          *
#   along with ReadOnMac. If not, see <http://www.gnu.org/licenses/>.          *
#                                                                              *
#*******************************************************************************

import objc, os, md5, mimetypes
from Foundation import *
from AppKit import *

class iReaderAppDelegate(NSObject):
    # Outlets
    webView = objc.IBOutlet()
    playPauseBtn = objc.IBOutlet()
    window = objc.IBOutlet()
    scrollSlider = objc.IBOutlet()
    
    # global variables
    rPath = NSBundle.mainBundle().resourcePath().fileSystemRepresentation()
    
    # internal variables
    scrollInterval = ""
    scrollValue = 30
    initialTitle = ""
    statusLine = ""

    def applicationDidFinishLaunching_(self, sender):
        """ load intro document """
        self.scrollValue = self.scrollSlider.intValue()
        self.initialTitle = self.window.title()
        self.webView.setMainFrameURL_('%s/beta.html' % self.rPath)

    def transformBook(self, fileName, mime):
        """ transform book from source, if needed """
        digest = md5.new(fileName).hexdigest()
        outFile = '%s/%s.html' % (self.rPath, digest)
        command = ""
        if mime == 'text/plain':
            command = 'echo "<meta http-equiv=\\"Content-Type\\" encoding=\\"text/html; charset: utf-8\\"/><pre>" > %s ; cat %s >> %s' % (outFile, fileName, outFile)
        else:
            command = 'xsltproc %s %s > %s' % ('%s/html.xsl' % self.rPath, fileName, outFile)
        os.system(command)
        return outFile

    def openBook(self, fileName):
        """ reset scroller, transform book, load book and show window """
        self.scrollStop_(self)
        mime = mimetypes.guess_type(fileName)[0]
        htmlFile = self.transformBook(fileName, mime)
        self.webView.setMainFrameURL_(htmlFile)
        self.window.setIsVisible_(objc.YES)
        self.window.setTitle_(u'%s — %s' % (self.initialTitle, fileName))
        self.statusLine = fileName

    @objc.IBAction
    def openBook_(self, sender):
        """ just ask for file """
        openDlg = NSOpenPanel.openPanel()
        if openDlg.runModal() == NSOKButton:
            files = openDlg.filenames()
            if files.count() == 1:
                self.openBook(files.objectAtIndex_(0))

    @objc.IBAction
    def scrollChange_(self, sender):
        """ change scroll speed """
        self.scrollValue = self.scrollSlider.intValue()
        if self.scrollInterval != "":
            self.scrollStop_(self)
            self.scrollStart_(self)

    @objc.IBAction
    def scrollFaster_(self, sender):
        """ make scroller slower """
        self.scrolValue = self.scrollValue - 5
        if self.scrollValue <= 5:
            self.scrollValue = 5
            return ""
        self.setScrollingSpeed()

    @objc.IBAction
    def scrollSlower_(self, sender):
        """ make scroller slower """
        self.scrolValue = self.scrollValue + 5
        if self.scrollValue >= 300:
            self.scrollValue = 300
            return ""
        self.setScrollingSpeed()
    
    def setScrollingSpeed(self):
        self.scrollSlider.setIntValue_(self.scrollValue)
        js = "window.scrollSpeed = %s;" % str(self.scrollValue)
        self.webView.stringByEvaluatingJavaScriptFromString_(js)
        if self.scrollInterval != "":
            self.scrollStop_(self)
            self.scrollStart_(self)
    
    @objc.IBAction
    def scrollStartStop_(self, sender):
        """ start or stop scrolling """
        if self.scrollInterval != "":
            self.scrollStop_(self)
        else:
            self.scrollStart_(self)

    @objc.IBAction
    def scrollStart_(self, sender):
        """ start scroller """
        if self.scrollInterval == "":
            self.playPauseBtn.setPaletteLabel_('Stop Scrolling')
            self.playPauseBtn.setLabel_('Stop Scrolling')
            self.playPauseBtn.setImage_(NSImage.alloc().initByReferencingFile_('%s/Pause.icns' % self.rPath))
            js = "window.scrollSpeed = %s; window.needScroll = true; setInterval(function () { if (window.needScroll) { window.scrollTo(0, window.scrollY + 1); } if (window.scrollY >= window.scrollMaxY) {window.needScroll = false; } }, window.scrollSpeed);" % str(self.scrollValue)
            self.scrollInterval = self.webView.stringByEvaluatingJavaScriptFromString_(js)

    @objc.IBAction
    def scrollStop_(self, sender):
        """ stop scrolling """
        if self.scrollInterval != "":
            self.playPauseBtn.setPaletteLabel_('Start Scrolling')
            self.playPauseBtn.setLabel_('Start Scrolling')
            self.playPauseBtn.setImage_(NSImage.alloc().initByReferencingFile_('%s/Play.icns' % self.rPath))
            js = "window.needScroll = false; clearInterval(%s);" % self.scrollInterval
            self.scrollInterval = self.webView.stringByEvaluatingJavaScriptFromString_(js)